package com.sogoodsoft.web.account;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;
import org.springside.modules.utils.web.struts2.Struts2Utils;

import com.sogoodsoft.dao.HibernateUtils;
import com.sogoodsoft.entity.account.Role;
import com.sogoodsoft.entity.account.User;
import com.sogoodsoft.entity.app.Organization;
import com.sogoodsoft.service.ServiceException;
import com.sogoodsoft.service.account.AccountManager;
import com.sogoodsoft.service.app.OrganizationService;
import com.sogoodsoft.util.DwzMsg;
import com.sogoodsoft.web.CrudActionSupport;
import com.sogoodsoft.web.WebConstants;

/**
 * 用户管理Action.
 * 
 * 使用Struts2 convention-plugin annotation定义Action参数. 演示带分页的管理界面.
 * 
 * @author calvin
 */
// 定义URL映射对应/account/user.action
@Namespace("/account")
// 定义名为reload的result重定向到user.action, 其他result则按照convention默认.
@Results({ @Result(name = CrudActionSupport.RELOAD, location = "user.action", type = "redirect"),
        @Result(name = "selectUser", location = "/WEB-INF/content/crm/selectUser.jsp"),
        @Result(name = "customerDispatch", location = "/WEB-INF/content/crm/customerDispatch.jsp"),
        
})
public class UserAction extends CrudActionSupport < User > {
    private static Log log = LogFactory.getLog(UserAction.class);

    private static final long serialVersionUID = 8683878162525847072L;

    private AccountManager accountManager;

    private OrganizationService orgSer;

    // -- 页面属性 --//
    private Long id;

    private User entity;

    private String passwordConfirm;

    private Long orgId;

    private Organization org;

    private Page < User > page = new Page < User >(WebConstants.PAGE_SIZE);// 每页14条记录

    private List < Long > checkedRoleIds; // 页面中钩选的角色id列表

    private List < Long > checkedIds;// 多选ID

    // -- ModelDriven 与 Preparable函数 --//
    public void setId(Long id) {
        this.id = id;
    }

    public User getModel() {
        return entity;
    }

    @Override
    protected void prepareModel() throws Exception {
        if (id != null) {
            entity = accountManager.getUser(id);
        } else {
            entity = new User();
        }
        if (orgId != null) {
            org = orgSer.get(orgId);
            entity.setOrganization(org);
        }
    }

    // -- CRUD Action 函数 --//
    @Override
    public String list() throws Exception {
        List < PropertyFilter > filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
        // 设置默认排序方式
        if (!page.isOrderBySetted()) {
            page.setOrderBy("id");
            page.setOrder(Page.DESC);
        }
        log.debug("查询用户列表");
        page = accountManager.searchUser(page, filters);
        return SUCCESS;
    }

    public String selectUser() throws Exception {
        list();
        return "selectUser";
    }
    
    public String customerDispatch() throws Exception {
        list();
        return "customerDispatch";
    }

    @Override
    public String input() throws Exception {
        checkedRoleIds = entity.getRoleIds();
        return INPUT;
    }

    @Override
    public String save() throws Exception {
        // 根据页面上的checkbox选择 整合User的Roles Set
        HibernateUtils.mergeByCheckedIds(entity.getRoleList(), checkedRoleIds, Role.class);

        accountManager.saveUser(entity);
        // addActionMessage("保存用户成功");

        // return RELOAD;
        Struts2Utils.renderJson(DwzMsg.successAndX(Struts2Utils.getParameter(DwzMsg.param_navTabId)));
        return null;
    }

    @Override
    public String delete() throws Exception {
        try {
            accountManager.deleteUser(id);
            // addActionMessage("删除用户成功");
        } catch (ServiceException e) {
            logger.error(e.getMessage(), e);
            addActionMessage("删除用户失败");
        }
        // return RELOAD;

        // Struts2Utils.renderJson(DwzMsg.successAndgo("account/user.action"));
        Struts2Utils.renderJson(DwzMsg.success());
        return null;
    }

    // 删除多用户
    public String deleteMuti() throws Exception {
        try {
            accountManager.deleteMutiUser(checkedIds);
            // addActionMessage("删除用户成功");
        } catch (ServiceException e) {
            logger.error(e.getMessage(), e);
            addActionMessage("删除用户失败");
        }
        return RELOAD;
    }

    // -- 其他Action函数 --//
    /**
     * 支持使用Jquery.validate Ajax检验用户名是否重复.
     */
    public String checkLoginName() {
        HttpServletRequest request = ServletActionContext.getRequest();
        String newLoginName = request.getParameter("loginName");
        String oldLoginName = request.getParameter("oldLoginName");

        if (accountManager.isLoginNameUnique(newLoginName, oldLoginName)) {
            Struts2Utils.renderText("true");
        } else {
            Struts2Utils.renderText("false");
        }
        // 因为直接输出内容而不经过jsp,因此返回null.
        return null;
    }

    // -- 页面属性访问函数 --//
    /**
     * list页面显示用户分页列表.
     */
    public Page < User > getPage() {
        return page;
    }

    /**
     * input页面显示所有角色列表.
     */
    public List < Role > getAllRoleList() {
        return accountManager.getAllRole();
    }

    /**
     * input页面显示用户拥有的角色.
     */
    public List < Long > getCheckedRoleIds() {
        return checkedRoleIds;
    }

    /**
     * input页面提交用户拥有的角色.
     */
    public void setCheckedRoleIds(List < Long > checkedRoleIds) {
        this.checkedRoleIds = checkedRoleIds;
    }

    public List < Long > getCheckedIds() {
        return checkedIds;
    }

    public void setCheckedIds(List < Long > checkedIds) {
        this.checkedIds = checkedIds;
    }

    @Autowired
    public void setAccountManager(AccountManager accountManager) {
        this.accountManager = accountManager;
    }

    public Long getOrgId() {
        return orgId;
    }

    public void setOrgId(Long orgId) {
        this.orgId = orgId;
    }

    public Organization getOrg() {
        return org;
    }

    public void setOrg(Organization org) {
        this.org = org;
    }

    public OrganizationService getOrgSer() {
        return orgSer;
    }

    @Autowired
    public void setOrgSer(OrganizationService orgSer) {
        this.orgSer = orgSer;
    }

    public String getPasswordConfirm() {
        return passwordConfirm;
    }

    public void setPasswordConfirm(String passwordConfirm) {
        this.passwordConfirm = passwordConfirm;
    }

}
